﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
using System.Collections;

namespace OptusMobile.Web.Handset
{
    public partial class BuyDetail : System.Web.UI.Page
    {
        private XmlDocument xmlDoc;

        int[] totalFee;
        //private int[] number;
        private int node = 0;

        Hashtable planValue;

        Hashtable handsetCount;

        public BuyDetail()
        {
            xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath("../Handset/ShoppingCarXML.xml"));
            //number = new int[xmlDoc.SelectSingleNode("item").ChildNodes.Count];
            
            planValue = new Hashtable();
            
            handsetCount = new Hashtable();
            
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string cssPath = "../css/BuyDetail.css";
            HtmlLink link = new HtmlLink();
            link.Href = cssPath;
            link.Attributes["rel"] = "stylesheet";
            link.Attributes["type"] = "text/css";
            PlaceHolder2.Controls.Add(link);

            Session["planValue"] = planValue;
            //Session["handsetCount"] = handsetCount;
            lblresult.Visible = false;
            if (Page.IsPostBack == false)
            { 
                ShowAllItem();
                //for (int i = 0; i < node; i++)
                //{
                //    TextBox txt = (TextBox)PlaceHolder1.FindControl("txt" + i.ToString());
                //    txt.Text = "1";
                //}
            }
            if (PlaceHolder1.HasControls() == false)
            {
                ShowAllItem();
            }
        }


        private int Calculation(int count)
        {
            int money = 0;
            int i = 0;
            if (((Hashtable)Session["planValue"]).Count > 0) 
            {
                totalFee = new int[((Hashtable)Session["planValue"]).Count];
                Hashtable ht = (Hashtable)Session["handsetCount"];
                Hashtable tplan = (Hashtable)Session["planValue"];
                foreach (DictionaryEntry tp in tplan)
                {
                    totalFee[i] = Convert.ToInt32(tp.Value);
                    i = i + 1;
                }
                i=0;
                foreach (DictionaryEntry de in ht)
                {
                    money = money + totalFee[i] * Convert.ToInt32(de.Value);
                    i = i + 1;
                }

            }
            return money;
        }

        private int CalculationCount(int count)
        {
            int num = 0;
            if (Page.IsPostBack == false)
            {
                for (int i = 0; i < count; i++)
                {
                    TextBox txt = (TextBox)PlaceHolder1.FindControl("txt" + i.ToString());

                    if (txt.Text == "")
                    {
                        txt.Text = "1";
                        handsetCount.Add(i, txt.Text);
                        Session["handsetCount"] = handsetCount;
                        continue;
                    }
                }
            }
           
            Hashtable ht = (Hashtable)Session["handsetCount"];
            foreach (DictionaryEntry de in ht)
            {
                num = Convert.ToInt32(de.Value) + num;
            }
            return num;
        
        }

        private int CalculationCountPostBack(string id,string value)
        {
            int num = 0;
            string keyvalue = id.Substring(3);
            handsetCount = (Hashtable)Session["handsetCount"];
            if (handsetCount.ContainsKey(Convert.ToInt32 ( keyvalue)))
            {
                handsetCount.Remove(Convert.ToInt32(keyvalue));
            }

            handsetCount.Add(Convert.ToInt32(keyvalue), value);
            Session["handsetCount"] = handsetCount;
            Hashtable ht = (Hashtable)Session["handsetCount"];
            foreach (DictionaryEntry de in ht)
            {
                num = Convert.ToInt32(de.Value) + num;
            }
            return num;


        }


        private void ShowAllItem()
        {
            PlaceHolder1.Controls.Clear();   
            HtmlGenericControl dynamicControl = new HtmlGenericControl();

            
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("item").ChildNodes;
            totalFee = new int[nodeList.Count];
            planValue.Clear();
            Session["planValue"] = planValue;
            int i = 0;
            foreach (XmlNode xn in nodeList)
            {
                XmlElement xe = (XmlElement)xn;
                if (xe.GetAttribute("ID") == Session.SessionID.ToString ())
                {

                    StringBuilder strHtml = new StringBuilder();
                    strHtml.Append("<tr id=\"imgarea\">");
                    strHtml.Append("<td>");
                    HtmlImage img = new HtmlImage();
                    img.ID = "imghandset" + i.ToString();
                    img.Src = xe.ChildNodes[1].InnerText;
                    img.Width = 45;
                    img.Height = 80;
                    img.EnableViewState = true;

                    Label lblhandset = new Label();
                    lblhandset.Text = xe.ChildNodes[4].InnerText;
                    lblhandset.CssClass = "lblhandset";
                    lblhandset.EnableViewState = true;

                    LinkButton btnrmove = new LinkButton();
                    btnrmove.ID = "btnrmove" + i.ToString();
                    btnrmove.Text = "Remove";
                    btnrmove.CssClass = "btn";
                    btnrmove.Command += new CommandEventHandler(btnrmove_Command);
                    btnrmove.CommandArgument = xe.ChildNodes[0].InnerText;
                    btnrmove.EnableViewState = true;

                    LinkButton btnUpdate = new LinkButton();
                    btnUpdate.ID = "btnupdate" + i.ToString();
                    btnUpdate.Text = "Update";
                    btnUpdate.CssClass = "btn";
                    //btnUpdate.Command += new CommandEventHandler(btnUpdate_Command);
                    //btnUpdate.CommandArgument = i.ToString();
                    btnUpdate.EnableViewState = true;
       

                    LiteralControl lc1 = new LiteralControl(strHtml.ToString());
                    lc1.EnableViewState = true;
                    dynamicControl.Controls.Add(lc1);
                    dynamicControl.Controls.Add(img);
                    dynamicControl.Controls.Add(lblhandset);
                    dynamicControl.Controls.Add(btnrmove);
                    dynamicControl.Controls.Add(btnUpdate);
                    strHtml.Remove(0, strHtml.Length);

                    strHtml.Append("</td>");
                    strHtml.Append("<td id=\"txtarea\">");
                    TextBox txt = new TextBox();
                    txt.ID = "txt" + i.ToString();
                    txt.TextChanged += new EventHandler(txt_TextChanged);
                    txt.EnableViewState = true;

                    LiteralControl lc2 = new LiteralControl(strHtml.ToString());
                    lc1.EnableViewState = true;
                    dynamicControl.Controls.Add(lc2);
                    dynamicControl.Controls.Add(txt);
                    strHtml.Remove(0, strHtml.Length);

                    strHtml.Append("</td>");
                    strHtml.Append("<td>");
                    strHtml.Append("</td>");
                    strHtml.Append("</tr>");
                    strHtml.Append("<tr id=\"planarea\">");
                    strHtml.Append("<td>");
                    HtmlImage planimg = new HtmlImage();
                    planimg.ID = "imgplan" + i.ToString();
                    planimg.Src = xe.ChildNodes[3].InnerText; ;
                    planimg.EnableViewState = true;

                    Label lblplan = new Label();
                    lblplan.Text = xe.ChildNodes[2].InnerText;
                    lblplan.CssClass = "lblplan";
                    lblplan.EnableViewState = true;

                    LiteralControl lc3 = new LiteralControl(strHtml.ToString());
                    lc1.EnableViewState = true;
                    dynamicControl.Controls.Add(lc3);
                    dynamicControl.Controls.Add(planimg);
                    dynamicControl.Controls.Add(lblplan);
                    strHtml.Remove(0, strHtml.Length);

                    strHtml.Append("</td>");
                    strHtml.Append("<td>");
                    strHtml.Append("</td>");
                    strHtml.Append("<td>");
                    Label lblplanmoney = new Label();
                    lblplanmoney.Text = xe.ChildNodes[2].InnerText.Substring(0, 2);
                    //totalFee[i] = Convert.ToInt32(lblplanmoney.Text);
                    planValue.Add(i, Convert.ToInt32(lblplanmoney.Text));
                    lblplanmoney.EnableViewState = true;
                    lblplanmoney.CssClass = "money";

                    LiteralControl lc4 = new LiteralControl(strHtml.ToString());
                    lc1.EnableViewState = true;
                    dynamicControl.Controls.Add(lc4);
                    dynamicControl.Controls.Add(lblplanmoney);
                    strHtml.Remove(0, strHtml.Length);

                    strHtml.Append("</td>");
                    strHtml.Append("</tr>");
                    LiteralControl lc5 = new LiteralControl(strHtml.ToString());
                    dynamicControl.Controls.Add(lc5);

                    PlaceHolder1.Controls.Add(dynamicControl);
                    i = i + 1;
                }
            }
            node = i;
            //if (Page.IsPostBack == false)
            //{ 
            //    totalQuantity.Text = CalculationCount(i).ToString();
            //}
            //else
            totalQuantity.Text = CalculationCount(i).ToString();
            totalMoney.Text= Calculation(i).ToString ();
            
            
        }

        void txt_TextChanged(object sender, EventArgs e)
        {
            //ShowAllItem();
            TextBox txt=sender as TextBox;
           
            Regex reg = new Regex("\\d");
            Match ma = reg.Match(txt.Text);
            if (ma.Success)
            {
                if (txt.Text.Length < 3)
                {
                    //totalFee = new int[xmlDoc.SelectSingleNode("item").ChildNodes.Count + Convert.ToInt32(txt.Text) - 1];

                    totalQuantity.Text = CalculationCountPostBack(txt.ID, txt.Text).ToString();
                    
                    totalMoney.Text = Calculation(node).ToString();

                }
            }
        }

        //void btnUpdate_Command(object sender, CommandEventArgs e)
        //{
        //    //ShowAllItem();
        //    //TextBox txt =(TextBox) PlaceHolder1.FindControl("txt"+e.CommandArgument.ToString());
        //    //Regex reg=new Regex("\\d");
        //    //Match ma=reg.Match(txt.Text );
        //    //if (ma.Success)
        //    //{
        //    //    if (txt.Text.Length <3)
        //    //    {
        //    //        totalQuantity.Text = CalculationCount(node).ToString();
        //    //        totalMoney.Text = Calculation(node).ToString();
                    
        //    //    }
        //    //}
           
        //}

        void btnrmove_Command(object sender, CommandEventArgs e)
        {
            handsetCount = (Hashtable)Session["handsetCount"];
            int deletnumber = 0;
            XmlNodeList xnl = xmlDoc.SelectSingleNode("item").ChildNodes;
            int i = 0;
            foreach (XmlNode xn in xnl)
            {
                XmlElement xe = (XmlElement)xn;

                if (xe.GetAttribute("ID") ==Session.SessionID)
                {
                    XmlNodeList nls = xe.ChildNodes;
                    foreach (XmlNode xn1 in nls)
                    {
                        XmlElement xe2 = (XmlElement)xn1;
                        if (xe2.InnerText == e.CommandArgument.ToString ())
                        {
                            
                            //xe.RemoveAll();
                            xe.ParentNode.RemoveChild(xe);
                            handsetCount.Remove(i);
                            deletnumber = i;
                            Session["handsetCount"] = handsetCount;
                            Session["item"] = Convert.ToInt32(Session["item"].ToString()) - 1;
                            i = i + 1;
                            //number[i] = 0;
                            break;

                        }
                    }
                    

                }
                
            }
            int j = 0;
            Hashtable hash = (Hashtable)Session["handsetCount"];
            Hashtable newtable = new Hashtable();
            foreach (DictionaryEntry de in hash)
            {
                newtable.Add(j, de.Value);
                j=j+1;
            }
            Session["handsetCount"] = newtable;
            xmlDoc.Save(Server.MapPath("../Handset/ShoppingCarXML.xml"));
            ShowAllItem();
            if (PlaceHolder1.Controls.Count > 0)
            {
                Hashtable ht = (Hashtable)Session["handsetCount"];
                
                foreach (DictionaryEntry de in ht)
                {
                    //TextBox txt = new TextBox();
                    //txt.Text = Convert.ToInt32(de.Value).ToString();
                    //if (deletnumber > Convert.ToInt32(de.Key))
                    //{
                    TextBox txt = new TextBox();
                    txt.Text = Convert.ToInt32(de.Value).ToString();
                    ((TextBox)PlaceHolder1.FindControl("txt" + (Convert.ToInt32(de.Key)).ToString())).Text = txt.Text;

                    //}

                    //if (deletnumber < Convert.ToInt32(de.Key))
                    //{
                    //    TextBox txt = new TextBox();
                    //    txt.Text = Convert.ToInt32(de.Value).ToString();
                    //    ((TextBox)PlaceHolder1.FindControl("txt" + (Convert.ToInt32(de.Key) - 1).ToString())).Text = txt.Text;

                    //}
                }
            }
        }

        protected void btnCheckOut_Click(object sender, EventArgs e)
        {
            lblresult.Visible = true;
            lblresult.Text = "Buy Successfully!  Thank you very much!";
            XmlNodeList xnl = xmlDoc.SelectSingleNode("item").ChildNodes;
            int count = xnl.Count;
            for (int i = 0; i < count; i++)
            {
                foreach (XmlNode xn in xnl)
                {
                    XmlElement xe = (XmlElement)xn;

                    if (xe.GetAttribute("ID") == Session.SessionID)
                    {
                        xe.ParentNode.RemoveChild(xe);
                    }
                }
            }
            xmlDoc.Save(Server.MapPath("../Handset/ShoppingCarXML.xml"));
            Session["item"] = "0";
        }
    }
}
